﻿using KAs.Application.Contract.Dto;
using KAs.Application.Contract.Svc;
using KAs.Common.Const;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace KAs.Api;

/// <summary>
/// 工具
/// </summary>
[Route(ConstConfig.API_ROUTE_CONFIG)]
[ApiController]
public class ToolController : ControllerBase
{
    private readonly ISqlSugarClient _db;
    private readonly IConfiguration _config;
    private readonly IAssembliesService _assemblies;

    public ToolController(ISqlSugarClient db, IConfiguration configuration, IAssembliesService assemblies)
    {
        _db = db;
        _config = configuration;
        _assemblies = assemblies;
    }

    /// <summary>
    /// 获取枚举
    /// </summary>
    /// <param name="key">枚举key值</param>
    /// <returns></returns>
    [HttpGet]
    public ApiResult<List<EnumDto>> GetEnums(string key)
    {
        if (key.IsNullOrWhiteSpace())
            return ApiResult<List<EnumDto>>.IsError("请传入正确的key值");

        var enumType = _assemblies.GetReadEnums().FirstOrDefault(x => x.Name.StartsWith(key));
        if (enumType != null)
        {
            var result = new List<EnumDto>();
            foreach (var enumItem in Enum.GetValues(enumType))
            {
                result.Add(new EnumDto()
                {
                    Key = enumType.Name,
                    EnumCode = Convert.ToInt32(enumItem),
                    EnumName = enumItem.ToString(),
                    EnumDesc = (enumItem as Enum).GetDescription()
                });
            }
            return ApiResult<List<EnumDto>>.IsSuccess(data: result);
        }
        return ApiResult<List<EnumDto>>.IsError("请传入正确的key值");
    }

    /// <summary>
    /// 初始化数据库
    /// </summary>
    /// <param name="pwd">密码</param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    public ApiResult<int> InitDataBase([FromBody] string pwd)
    {
        try
        {
            if (pwd == _config["InitDbPwd"])
            {
                // 若数据库不存在，创建数据库
                _db.DbMaintenance.CreateDatabase();
                // 创建或更新数据结构
                var entityTypes = _assemblies.GetEntities();
                _db.CodeFirst.SetStringDefaultLength(64).InitTables(entityTypes.ToArray());
                // 插入配置数据
                // 判断配置数据是否存在，插入或更新等，
                // 建议此处使用sql语句而不是实体，因为该类库是没有实际业务的，会造成循环引用
                // ......
                //string sql = @"";
                //_db.Ado.ExecuteCommand(sql);
                return ApiResult<int>.IsSuccess();
            }
            else
            {
                return ApiResult<int>.IsError();
            }
        }
        catch (Exception ex)
        {
            return ApiResult<int>.IsError(ex.Message);
        }
    }

    /// <summary>
    /// 健康检查
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public ApiResult<bool> CheckHealth()
    {
        return ApiResult<bool>.IsSuccess();
    }
}
